package com.wondertek.poms.dao.repo.es.impl;

import com.wondertek.poms.common.utils.DateUtil;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.dao.po.ForCisLog;
import com.wondertek.poms.dao.repo.ISystemConfigDao;
import com.wondertek.poms.dao.repo.es.IForCisLogESDao;
import com.wondertek.poms.dao.util.ESUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chenjijiang
 * @description
 */
@Slf4j
@Component
public class ForCisLogESDaoImpl implements IForCisLogESDao {
	@Autowired
	private ISystemConfigDao systemConfigDao;

	@Override
	public List<ForCisLog> getBcLog(Map<String, String> map, int start, int limit) {
		String index_name = StringUtil.null2Str(systemConfigDao.findByCkey("Index_PrdContDao"));
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("ForCisLog").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();
		if (!StringUtil.isNullStr(map.get("prdContId"))) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(map.get("prdContId"))));
		}

		if (!StringUtil.isNullStr(map.get("uuid"))) {
			qb.must(QueryBuilders.termQuery("UUID", StringUtil.nullToString(map.get("uuid"))));

		}

		if (!StringUtil.isNullStr(map.get("mediaFileId"))) {
			qb.must(QueryBuilders.termQuery("MEDIA_FILE_ID", StringUtil.nullToString(map.get("mediaFileId"))));
		}

		if (!StringUtil.isNullStr(map.get("isFreetrial"))) {
			qb.must(QueryBuilders.termQuery("IS_FREE_TRIAL", StringUtil.nullToString(map.get("isFreetrial"))));

		}

		if (!StringUtil.isNullStr(map.get("operation"))) {
			qb.must(QueryBuilders.termQuery("OPERATION", StringUtil.nullToString(map.get("operation"))));

		}

		if (!StringUtil.isNullStr(map.get("responseStatus"))) {
			qb.must(QueryBuilders.termQuery("RESPONSE_STATUS", StringUtil.nullToString(map.get("responseStatus"))));
		}

		if (!StringUtil.isNullStr(map.get("auditStatus"))) {
			qb.must(QueryBuilders.termQuery("AUDIT_STATUS", StringUtil.nullToString(map.get("auditStatus"))));

		}
		if (StringUtil.isNullStr(map.get("prdContId")) && StringUtil.isNullStr(map.get("uuid"))) {
			if (StringUtil.isNullStr(map.get("startTime")) && StringUtil.isNullStr(map.get("endTime"))) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DAY_OF_MONTH, -2);
				Date startDate = cal.getTime();
				cal.add(Calendar.DAY_OF_MONTH, +3);
				Date endDate = cal.getTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				qb.filter(QueryBuilders.rangeQuery("CREATE_TIME").from(sdf.format(startDate)).includeLower(true)
						.to(sdf.format(endDate)).includeUpper(true));

			} else if (!StringUtil.isNullStr(map.get("startTime")) && !StringUtil.isNullStr(map.get("endTime"))) {
				String st = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.parseDate("yyyy-MM-dd", map.get("startTime")));
				Calendar cal = Calendar.getInstance();
				cal.setTime(DateUtil.parseDate("yyyy-MM-dd", map.get("endTime")));
				cal.add(Calendar.DAY_OF_MONTH, +1);
				String et = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
				qb.filter(QueryBuilders.rangeQuery("CREATE_TIME").from(st).includeLower(true).to(et).includeUpper(true));
			} else if (!StringUtil.isNullStr(map.get("startTime")) && StringUtil.isNullStr(map.get("endTime"))) {
				String st = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.parseDate("yyyy-MM-dd", map.get("startTime")));
				qb.must(QueryBuilders.rangeQuery("CREATE_TIME").from(st).includeLower(true));

			} else if (StringUtil.isNullStr(map.get("startTime")) && !StringUtil.isNullStr(map.get("endTime"))) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(DateUtil.parseDate("yyyy-MM-dd", map.get("endTime")));
				cal.add(Calendar.DAY_OF_MONTH, +1);
				String et = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
				qb.must(QueryBuilders.rangeQuery("CREATE_TIME").to(et).includeUpper(true));

			}
		}
		builder.addSort(SortBuilders.fieldSort("ID").order(SortOrder.DESC));
		if (start == 0 && limit == 0) {
			builder.setQuery(qb);
		} else {
			builder.setQuery(qb).setFrom(start).setSize(limit);
		}

		log.info("=====GETLIST Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();
		List<ForCisLog> forCisLogs = new ArrayList<ForCisLog>();
		for (SearchHit hit : hits.getHits()) {
			ForCisLog log = new ForCisLog();
			log.setId(StringUtil.nullToLong(hit.getSource().get("ID")));
			log.setAuditStatus(StringUtil.nullToString(hit.getSource().get("AUDIT_STATUS")));
			log.setCreateTime(StringUtil.nullToDate(hit.getSource().get("CREATE_TIME"), "yyyy-MM-dd'T'HH:mm:ss"));
			log.setIsFreetrial(StringUtil.nullToString(hit.getSource().get("IS_FREE_TRIAL")));
			log.setMediaFileId(StringUtil.nullToString(hit.getSource().get("MEDIA_FILE_ID")));
			log.setOperation(StringUtil.nullToString(hit.getSource().get("OPERATION")));
			log.setPrdContId(StringUtil.nullToLong(hit.getSource().get("PRD_CONT_ID")));
			log.setResponseMessage(StringUtil.nullToString(hit.getSource().get("RESPONSE_MESSAGE")));
			log.setResponseTime(StringUtil.nullToString(hit.getSource().get("RESPONSE_TIME")).replace("T", " "));
			log.setUuid(StringUtil.nullToString(hit.getSource().get("UUID")));
			forCisLogs.add(log);
		}
		return forCisLogs;
	}

	@Override
	public long getBcLogCount(Map<String, String> map) {
		String index_name = StringUtil.null2Str(systemConfigDao.findByCkey("Index_PrdContDao"));
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("ForCisLog").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();
		if (!StringUtil.isNullStr(map.get("prdContId"))) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(map.get("prdContId"))));
		}

		if (!StringUtil.isNullStr(map.get("uuid"))) {
			qb.must(QueryBuilders.termQuery("UUID", StringUtil.nullToString(map.get("uuid"))));

		}

		if (!StringUtil.isNullStr(map.get("mediaFileId"))) {
			qb.must(QueryBuilders.termQuery("MEDIA_FILE_ID", StringUtil.nullToString(map.get("mediaFileId"))));
		}

		if (!StringUtil.isNullStr(map.get("isFreetrial"))) {
			qb.must(QueryBuilders.termQuery("IS_FREE_TRIAL", StringUtil.nullToString(map.get("isFreetrial"))));

		}

		if (!StringUtil.isNullStr(map.get("operation"))) {
			qb.must(QueryBuilders.termQuery("OPERATION", StringUtil.nullToString(map.get("operation"))));

		}

		if (!StringUtil.isNullStr(map.get("responseStatus"))) {
			qb.must(QueryBuilders.termQuery("RESPONSE_STATUS", StringUtil.nullToString(map.get("responseStatus"))));
		}

		if (!StringUtil.isNullStr(map.get("auditStatus"))) {
			qb.must(QueryBuilders.termQuery("AUDIT_STATUS", StringUtil.nullToString(map.get("auditStatus"))));

		}
		if (StringUtil.isNullStr(map.get("prdContId")) && StringUtil.isNullStr(map.get("uuid"))) {
			if (StringUtil.isNullStr(map.get("startTime")) && StringUtil.isNullStr(map.get("endTime"))) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DAY_OF_MONTH, -2);
				Date startDate = cal.getTime();
				cal.add(Calendar.DAY_OF_MONTH, +3);
				Date endDate = cal.getTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				qb.filter(QueryBuilders.rangeQuery("CREATE_TIME").from(sdf.format(startDate)).includeLower(true)
						.to(sdf.format(endDate)).includeUpper(true));

			} else if (!StringUtil.isNullStr(map.get("startTime")) && !StringUtil.isNullStr(map.get("endTime"))) {
				String st = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.parseDate("yyyy-MM-dd", map.get("startTime")));
				Calendar cal = Calendar.getInstance();
				cal.setTime(DateUtil.parseDate("yyyy-MM-dd", map.get("endTime")));
				cal.add(Calendar.DAY_OF_MONTH, +1);
				String et = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
				qb.filter(QueryBuilders.rangeQuery("CREATE_TIME").from(st).includeLower(true).to(et).includeUpper(true));
			} else if (!StringUtil.isNullStr(map.get("startTime")) && StringUtil.isNullStr(map.get("endTime"))) {
				String st = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.parseDate("yyyy-MM-dd", map.get("startTime")));
				qb.must(QueryBuilders.rangeQuery("CREATE_TIME").from(st).includeLower(true));

			} else if (StringUtil.isNullStr(map.get("startTime")) && !StringUtil.isNullStr(map.get("endTime"))) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(DateUtil.parseDate("yyyy-MM-dd", map.get("endTime")));
				cal.add(Calendar.DAY_OF_MONTH, +1);
				String et = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
				qb.must(QueryBuilders.rangeQuery("CREATE_TIME").to(et).includeUpper(true));

			}
		}
		builder.setQuery(qb);
		log.info("index_name:" + index_name + "=====Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();
		log.info("====hits.getTotalHits:====" + hits.getTotalHits());
		return hits.getTotalHits();
	}
}
